package com.qf.mprefer.user.interceptor;


import com.qf.mprefer.ex.QFException;
import com.qf.mprefer.utils.CommonConstants;
import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 检查请求中的token是否合法
 */
@Component
public class TokenInterCeptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 放行 浏览器的跨域 OPTIONS 请求
        final String method = request.getMethod();
        if (method.equals("OPTIONS")){
            return true;
        }

        final String token = request.getHeader("token");

        final JwtParser parser = Jwts.parser();
        parser.setSigningKey(CommonConstants.JWT_SECRET_KEY);

        try {
            final Jwt jwt = parser.parse(token);
        }  catch (Exception e) {
            throw new QFException("token 有问题！请重新登录");
        }

        // 把请求放行
        return true;
    }
}
